package net.synck.gcontacts.editor;

import java.util.Map;

import net.synck.gcontacts.tools.RelTools;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;

import com.google.gdata.data.extensions.Email;

public class EmailDetailsPage implements IDetailsPage {
	private IManagedForm mform;
	private Email input;
		
	private Composite compositeEmailDetails = null;
	private Label labelAdressEmail = null;
	private Label labelEmailType = null;
	private Label labelEmailPrimary = null;
	private Label labelEmailLabel = null;
	private Text textEmailLabel = null;
	private Text textEmailAdress = null;
	private Combo comboEmailType = null;
	private Button checkBoxEmailPrimary = null;

	boolean lockUISelection = false;

	private boolean isDirty;
	private boolean isUpdateInProgress;
	
	@Override
	public void createContents(Composite parent) {
		System.out.println("EmailDetailsPage.createContents()");
		createCompositeEmailDetails(parent);
	}

	@Override
	public void commit(boolean onSave) {
		System.out.println("commit email details: onSave == " + onSave);
		
		input.setAddress(textEmailAdress.getText());
		input.setRel(ComboboxContentWrapper.getKeyByIndex(RelTools.getEmailRel(), comboEmailType.getSelectionIndex()));
		input.setPrimary(checkBoxEmailPrimary.getSelection());
		
		if (!textEmailLabel.getText().isEmpty()) {
			input.setLabel(textEmailLabel.getText());
		} else {
			input.setLabel(null);
		}
		
		if (onSave) {
			isDirty = false;		
		}
		
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
	}

	@Override
	public void initialize(IManagedForm form) {
		System.out.println("EmailDetailsPage.initialize()");
		this.mform = form;
	}

	@Override
	public boolean isDirty() {
		System.out.println("EmailDetailsPage.isDirty()");
		return isDirty;
	}

	@Override
	public boolean isStale() {
		System.out.println("EmailDetailsPage.isStale()");
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void refresh() {
		System.out.println("EmailDetailsPage.refresh()");
		// TODO Auto-generated method stub

	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean setFormInput(Object input) {
		this.input = (Email)input;
		return true;
	}

	@Override
	public void selectionChanged(IFormPart part, ISelection selection) {
		System.out.println("EmailDetailsPage.selectionChanged()");
		IStructuredSelection ssel = (IStructuredSelection)selection;
		if (ssel.size()==1) {
			input = (Email)ssel.getFirstElement();
		}
		else
			input = null;
		update();
	}

	private void update() {
		System.out.println("EmailDetailsPage.update()");
		isUpdateInProgress = true;
		textEmailAdress.setText(input.getAddress());		
		comboEmailType.clearSelection();
		comboEmailType.setItems(ComboboxContentWrapper.getValues(RelTools.getEmailRel()));
		comboEmailType.select(ComboboxContentWrapper.getIndexByKey(RelTools.getEmailRel(), input.getRel()));
		checkBoxEmailPrimary.setSelection(input.getPrimary());
		if (input.getLabel() != null) {
			textEmailLabel.setText(input.getLabel());
		} else {
			textEmailLabel.setText("");
		}
		isUpdateInProgress = false;
	}
	
	private static class ComboboxContentWrapper {
		
		//FIX ME!!! order in a set is not guaranteed ! 
		public static String[] getValues(Map<String,String> data) {
			return (String[]) data.values().toArray(new String[data.values().size()]);
		}
		
		public static int getIndexByKey(Map<String,String> data, String key) {
			if (key == null)
				return -1;
			int i = 0;
			for (String s : data.keySet()) {
				if (key.equals(s)) {
					return i; 
				}
				i++;
			}			
			return -1;
		}
		
		public static String getKeyByIndex(Map<String,String> data, int index) {
			int i = 0;
			for (String s : data.keySet()) {
				if (i == index)
					return s;
				i++;
			}
			return null;
		} 
		
	}
	
	/**
	 * This method initializes compositeEmailDetails	
	 *
	 */
	private void createCompositeEmailDetails(Composite parent) {
		
		TableWrapLayout layout = new TableWrapLayout();
		layout.topMargin = 5;
		layout.leftMargin = 5;
		layout.rightMargin = 2;
		layout.bottomMargin = 2;
		parent.setLayout(layout);

		FormToolkit toolkit = mform.getToolkit();
		Section s1 = toolkit.createSection(parent, Section.DESCRIPTION|Section.TITLE_BAR);
		s1.marginWidth = 10;
		s1.setText("Email"); //$NON-NLS-1$
		s1.setDescription("Email details"); //$NON-NLS-1$
		TableWrapData td = new TableWrapData(TableWrapData.FILL, TableWrapData.TOP);
		td.grabHorizontal = true;
		s1.setLayoutData(td);
		
		
		GridData gridData8 = new GridData();
		gridData8.horizontalAlignment = GridData.FILL;
		gridData8.grabExcessHorizontalSpace = true;
		gridData8.verticalAlignment = GridData.CENTER;

		GridData gridData9 = new GridData();
		gridData9.horizontalAlignment = GridData.FILL;
		gridData9.grabExcessHorizontalSpace = true;
		gridData9.verticalAlignment = GridData.CENTER;
		
		
		GridLayout gridLayout3 = new GridLayout();		
		gridLayout3.numColumns = 2;
		
		GridData gridData7 = new GridData();
		gridData7.horizontalAlignment = GridData.FILL;
		gridData7.grabExcessHorizontalSpace = true;
		gridData7.verticalAlignment = GridData.FILL;
		
		compositeEmailDetails = getFormToolkit().createComposite(s1);
		compositeEmailDetails.setLayoutData(gridData7);
		compositeEmailDetails.setLayout(gridLayout3);
		
		labelAdressEmail = getFormToolkit().createLabel(compositeEmailDetails, "Address:");
		textEmailAdress = getFormToolkit().createText(compositeEmailDetails, null, SWT.SINGLE | SWT.BORDER);
		textEmailAdress.setLayoutData(gridData8);
		
		labelEmailType = getFormToolkit().createLabel(compositeEmailDetails, "Type:");		
		createComboEmailType();
		
		labelEmailLabel = getFormToolkit().createLabel(compositeEmailDetails, "Label:");
		textEmailLabel = getFormToolkit().createText(compositeEmailDetails, null, SWT.SINGLE | SWT.BORDER);
		textEmailLabel.setLayoutData(gridData9);
		
		labelEmailPrimary = getFormToolkit().createLabel(compositeEmailDetails, "Primary:");
		checkBoxEmailPrimary = getFormToolkit().createButton(compositeEmailDetails, null, SWT.CHECK);
		
		toolkit.paintBordersFor(s1);
		s1.setClient(compositeEmailDetails);
		
		
		
		textEmailAdress.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent e) {
				setDirty(true);
			}			
		});
		
		
		
		textEmailLabel.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent e) {
				if (lockUISelection) return;
				lockUISelection = true;				
				comboEmailType.select(0);
				setDirty(true);
				lockUISelection = false;
			}			
		});
		
		comboEmailType.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (lockUISelection) return;
				lockUISelection = true;				
				if (comboEmailType.getSelectionIndex() != 0) {
					textEmailLabel.setText("");
				}
				setDirty(true);			
				lockUISelection = false;
			}			
		});
		
		checkBoxEmailPrimary.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub				
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				setDirty(true);
			}			
		} );
	}
	
	private void setDirty(boolean dirty) {
		if (!isUpdateInProgress) {
			isDirty = dirty;
			mform.dirtyStateChanged();
		}
	}
	
	private FormToolkit getFormToolkit() {
		return mform.getToolkit();
	}

	/**
	 * This method initializes comboEmailType	
	 *
	 */
	private void createComboEmailType() {
		GridData gridData9 = new GridData();
		gridData9.horizontalAlignment = GridData.FILL;
		gridData9.verticalAlignment = GridData.CENTER;
		comboEmailType = new Combo(compositeEmailDetails, SWT.NONE | SWT.READ_ONLY);
		comboEmailType.setLayoutData(gridData9);
		
	}
	
}
